<template>
  <view class="login">
    <view class="head">
      <text>您好，</text>
      <text>
        <text>欢迎来到 </text>
        <text class="green">集鲜直采</text>
      </text>
    </view>
    <view class="shadow">
      <view class="identity-tab">
        <view
          :class="{ 'tab-active': loginType === item.type, tab: true }"
          v-for="item in loginTypeList"
          :key="item.name"
          @click="changeLoginType(item.type)"
        >
          {{ item.name }}
        </view>
      </view>
    </view>
    <view class="form">
      <u-form :model="form" ref="uForm" :label-width="64">
        <template v-if="loginType === 'byUsername'">
          <u-form-item
            :height="110"
            :left-icon="userIcon"
            :left-icon-style="{
              width: '36rpx',
              position: 'relative',
              top: '8rpx',
              margin: '0 4rpx'
            }"
          >
            <u-input
              placeholder="请输入用户名"
              placeholder-style="font-weight: 400 !important"
              :clearable="true"
              v-model="form.username"
              :focus="focusPhone"
              @blur="focusPhone = false"
              @confirm="focusPhone = false"
              @focus="focusPhone = true"
            />
          </u-form-item>
          <u-form-item
            :height="110"
            :left-icon="psdUrl"
            :left-icon-style="{
              width: '30rpx',
              position: 'relative',
              top: '8rpx',
              margin: '0 7rpx'
            }"
          >
            <input
              class="hidden_input"
              :focus="focusState"
              placeholder=""
              v-model="form.psd"
              @blur="focusState = false"
              @confirm="focusState = false"
            />
            <view class="show_input" @click="handleFocusInput">
              <view class="custom-ph" v-if="!form.psd && !focusState"
                >请输入密码</view
              >
              <template v-else>
                <view class="custom_pw">{{
                  showPwd ? form.psd : form.psd?.replace(/\S|\s/g, '*')
                }}</view>
                <view class="cursor" v-show="focusState"></view>
                <uni-icons
                  v-show="focusState && form.psd"
                  class="icon"
                  :type="showPwd ? 'eye-filled' : 'eye'"
                  size="13"
                  @click="showPwd = !showPwd"
                ></uni-icons>
              </template>
            </view>
          </u-form-item>
          <u-form-item
            v-if="needVerifyCode"
            :height="110"
            :left-icon="codeIcon"
            :left-icon-style="{
              width: '36rpx',
              position: 'relative',
              top: '8rpx',
              margin: '0 4rpx'
            }"
          >
            <u-input
              placeholder="请输入验证码"
              v-model="form.code"
              :password-icon="!!form.psd"
              placeholder-style="font-weight: 400 !important"
            />
            <template #right>
              <u-button
                type="primary"
                :disabled="getCodeBtnDisable"
                size="mini"
                @click.stop="getCaptcha"
              >
                {{ codeBtnWord }}
              </u-button>
            </template>
          </u-form-item>
        </template>
        <template v-else>
          <u-form-item
            :height="110"
            :left-icon="phoneUrl"
            :left-icon-style="{
              width: '26rpx',
              position: 'relative',
              top: '8rpx',
              margin: '0 9rpx'
            }"
          >
            <u-input
              placeholder="请输入手机号码"
              placeholder-style="font-weight: 400 !important"
              :clearable="true"
              v-model="form.phone"
            />
          </u-form-item>
          <u-form-item
            :height="110"
            :left-icon="codeIcon"
            :left-icon-style="{
              width: '36rpx',
              position: 'relative',
              top: '8rpx',
              margin: '0 4rpx'
            }"
          >
            <u-input
              placeholder="请输入验证码"
              v-model="form.code"
              :password-icon="!!form.psd"
              placeholder-style="font-weight: 400 !important"
            />
            <template #right>
              <u-button
                type="primary"
                :disabled="getCodeBtnDisable"
                size="mini"
                @click.stop="getCaptcha"
              >
                {{ codeBtnWord }}
              </u-button>
            </template>
          </u-form-item>
        </template>
      </u-form>
      <view class="agreement">
        <u-checkbox-group shape="circle" active-color="#04B27C" :icon-size="32">
          <u-checkbox v-model="agree" :icon-size="32">
            <text style="font-size: 24rpx">
              我已经阅读并同意
              <text class="prot" @click="jumpPrivacy">《服务协议》</text>
            </text>
          </u-checkbox>
        </u-checkbox-group>
      </view>
      <view>
        <u-button
          type="primary"
          :loading="loading"
          :disabled="disabled || loading"
          @click="submit"
        >
          登录
        </u-button>
      </view>
      <view class="one-key-login">
        <u-button
          ref="quickLoginBtn"
          @click="handleOneKeyLogin"
          :loading="loadingOneKey"
          class="btn-style-1 one-key-btn"
          >一键登录</u-button
        >
      </view>
    </view>
    <u-modal
      v-model:visible="visible"
      title="阅读协议"
      confirm-text="立即登录"
      cancel-text="暂不登录"
      @confirm="handleConfirm"
    >
      <view>
        <text>我已阅读并同意</text>
        <text style="color: #04b27c" @click="jumpPrivacy"
          >《集鲜直采的服务协议》</text
        >。
      </view>
    </u-modal>
    <u-modal
      v-model:visible="phoneVisible"
      title="一键登录"
      confirm-text="立即绑定"
      cancel-text="暂不绑定"
    >
      <view>
        <text>初次使用需要绑定手机号</text>
      </view>
      <template #confirm-button>
        <button
          class="phone-button"
          open-type="getPhoneNumber"
          @getphonenumber="getPhoneNumber"
        >
          立即绑定
        </button>
      </template>
    </u-modal>
    <privacy-authorization-modal />
  </view>
  <u-select
    v-model="showTenant"
    :list="tenantList"
    @confirm="tenantConfirm"
  ></u-select>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useStore } from 'vuex'
import { onShow, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'
import phoneUrl from '../../assets/imgs/phone.svg'
import psdUrl from '../../assets/imgs/psd.svg'
import codeIcon from '../../assets/imgs/icon-input-code.png'
import userIcon from '../../assets/imgs/icon-input-user.png'
import { checkPhone } from '../../utils/check'
import {
  loginApplet,
  getUserInfo,
  getTenantsByPhone,
  miniTenantChange,
  sendVerifyCode,
  vaildBindPhoneApi,
  bindAppIdApi
} from '@/api/user'
import { removeStorage } from '@/utils/http'
import { report } from '@/utils/track'
import { clearStorage } from '@/utils/auth'

const loginTypeList = [
  { name: '账号密码登录', type: 'byUsername' },
  { name: '验证码登录', type: 'byCode' }
]

const form = ref<{
  username: string
  phone: any
  psd: any
  code?: any
}>({
  username: '',
  phone: '',
  psd: '',
  code: ''
})
const loginStyle = ref('password')
const visible = ref(false)
const phoneVisible = ref(false)
const store = useStore()
const uForm = ref()
const loading = ref(false)
const loadingOneKey = ref(false)
const agree = ref(false)
const quickLoginBtn = ref(null)
const loginType = ref('byUsername')
const codeBtnWord = ref('获取验证码')
const getCodeBtnDisable = ref(false)
const waitTime = ref(60)
const needVerifyCode = ref(false)
const disabled = computed(() => {
  if (loginType.value === 'byCode') {
    return !form.value.phone || !form.value.code
  }
  if (loginType.value === 'byUsername') {
    if (needVerifyCode.value) {
      return !form.value.username || !form.value.psd || !form.value.code
    }
    return !form.value.username || !form.value.psd
  }
  return false
})
let timer: any
console.log(store)

store.commit('user/INIT_EQUIPMENT')
onShow(() => {
  removeStorage()
})

const focusPhone = ref(false)
const focusState = ref(false)
const showPwd = ref(false)
function handleFocusInput() {
  focusState.value = true
}

function getSupplierCode() {
  const launchOptions = uni.getEnterOptionsSync()
  const { query } = launchOptions
  return query.scene
}

function changeLoginType(type: string) {
  if (type !== loginType.value) {
    loginType.value = type
    form.value.username = undefined
    form.value.phone = undefined
    form.value.psd = undefined
    form.value.code = undefined
    timer && clearInterval(timer)
    waitTime.value = 60
    getCodeBtnDisable.value = false
    codeBtnWord.value = '获取验证码'
    needVerifyCode.value = false
  }
}

// 获取验证码
async function getCaptcha() {
  let msg = ''
  if (getCodeBtnDisable.value) return
  if (!form.value.phone) {
    msg = '手机号码不能为空'
  } else if (!checkPhone(form.value.phone)) {
    msg = '请输入合法手机号码'
  }
  if (msg) {
    uni.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      position: 'top'
    })
    return
  }
  try {
    await sendVerifyCode({ phone: form.value.phone })
    uni.showToast({
      title: '验证码发送成功',
      icon: 'none',
      duration: 2000,
      position: 'top'
    })
    waitTime.value -= 1
    getCodeBtnDisable.value = true
    codeBtnWord.value = `${waitTime.value}s 后重新发送`
    timer = setInterval(() => {
      if (waitTime.value > 1) {
        waitTime.value -= 1
        codeBtnWord.value = `${waitTime.value}s 后重新发送`
      } else {
        clearInterval(timer)
        codeBtnWord.value = '获取验证码'
        getCodeBtnDisable.value = false
        waitTime.value = 60
      }
    }, 1000)
  } catch (e: any) {
    if (e.data.data.code === 1) {
      uni.showToast({
        title: e.data.data.msg,
        icon: 'none',
        duration: 2000,
        position: 'top'
      })
    }
  }
}

const tenantList = ref()
const showTenant = ref(false)
function selectTenant() {
  const phone = store.state.user.userInfo?.sysUser?.phone
  getTenantsByPhone({
    phone,
    identity: [] // AUTO
  }).then((res: any) => {
    const data = res.data || []
    tenantList.value = data.map((item: any) => ({
      label: item.tenantName,
      value: item.username
    }))
    if (tenantList.value.length > 1) {
      showTenant.value = true
    } else {
      uni.navigateTo({
        url: '/pages/product/index'
      })
    }
  })
}

function bindAppId(userId: string) {
  uni.login({
    success(result) {
      const params = {
        userId,
        code: result.code
      }
      bindAppIdApi(params)
    }
  })
}
function tenantConfirm(row: any) {
  miniTenantChange(row[0].value, store.state.user.equipment).then(
    async (res: any) => {
      uni.setStorageSync('token', `${res.token_type} ${res.access_token}`)
      uni.setStorageSync('tenant_id', `${res.tenant_id}`)
      const userInfo = await getUserInfo()
      bindAppId(userInfo.data.sysUser.userId)
      store.commit('user/SET_USERINFO', userInfo.data)
      if (userInfo.data.sysUser.supplierCode) {
        uni.setStorageSync('supplier_code', userInfo.data.sysUser.supplierCode)
      }
      uni.navigateTo({
        url: '/pages/product/index'
      })
    }
  )
}

let isWXLogin = false

async function login() {
  loading.value = true
  isWXLogin = false
  try {
    clearStorage()
    await store.dispatch('user/login', {
      username: form.value.username,
      password: form.value.psd,
      phone: form.value.phone,
      code: form.value.code,
      loginType: loginType.value,
      supplierCode: getSupplierCode(),
      selectTenant
    })
  } catch (e: any) {
    if (e?.msg === '更换设备登录需要手机验证码校验') {
      needVerifyCode.value = true
      form.value.phone = e.data
      getCaptcha()
    }
  } finally {
    loading.value = false
  }
}
function submit() {
  loginStyle.value = 'password'
  if (!agree.value) {
    visible.value = true
    return
  }
  login()
}

const jumpPrivacy = () => {
  uni.navigateTo({
    url: '/pages/privacy/index'
  })
}
// eslint-disable-next-line consistent-return
const handleLogin = async ({ code, mobile, iv }: any) => {
  isWXLogin = true
  clearStorage()
  const res: any = await loginApplet({
    code,
    mobile,
    iv,
    supplier_code: getSupplierCode(),
    equipment: store.state.user.equipment
  })
  uni.hideLoading()
  if (res?.data === 'account_not_bound_exception') {
    phoneVisible.value = true
    return false
  }
  if (res?.data === 'account_not_find_exception') {
    uni.showToast({
      title: '该用户没有访问权限',
      duration: 2000,
      icon: 'none'
    })
    return false
  }
  if (res?.data === 'tenant_not_find_exception') {
    uni.showToast({
      title: '店铺已关闭或已不存在',
      duration: 2000,
      icon: 'none'
    })
    return false
  }
  if (res) {
    try {
      uni.setStorageSync('token', `${res.token_type} ${res.access_token}`)
      uni.setStorageSync('tenant_id', `${res.tenant_id}`)
      const userInfo = await getUserInfo()
      store.commit('user/SET_USERINFO', userInfo.data)
      if (userInfo.data.sysUser.supplierCode) {
        uni.setStorageSync('supplier_code', userInfo.data.sysUser.supplierCode)
      }
      selectTenant()
      report({ name_zh: '登陆', name: isWXLogin ? '一键登录' : '登录' })
    } finally {
      //
    }
  }
}

const getWxCode = async () => {
  return new Promise((resolve, reject) => {
    uni.login({
      provider: 'weixin',
      onlyAuthorize: true,
      success: async ({ code }) => {
        resolve(code)
      },
      fail: (err) => {
        reject(err)
      }
    })
  })
}

const vaildBindCode = async () => {
  return new Promise(async (resolve, reject) => {
    try {
      const code = await getWxCode()
      const res = await vaildBindPhoneApi({
        identity: 'MINI_OLD', // MINI_OLD 最开始的小程序 MINI_PROCURE 直采 MINI_SUPPLIER 直供
        code
      })
      resolve(res.data)
    } catch (e) {
      reject(e)
    }
  })
}

const handleOneKeyLogin = async () => {
  try {
    loginStyle.value = 'applet'
    if (!agree.value) {
      visible.value = true
      return
    }
    const valid = await vaildBindCode()
    if (!valid) {
      phoneVisible.value = true
      return
    }
    loadingOneKey.value = true
    uni.showLoading({
      title: '加载中'
    })
    const code = await getWxCode()
    uni.hideToast()
    await handleLogin({ code })
  } finally {
    //
  }
  loadingOneKey.value = false
}

const getPhoneNumber = async (e: any) => {
  if (e.detail.errMsg === 'getPhoneNumber:ok') {
    const { encryptedData, iv } = e.detail || {}
    phoneVisible.value = false
    const code = await getWxCode()
    handleLogin({ code, mobile: encryptedData, iv })
  } else if (e.detail.errMsg === 'getPhoneNumber:fail user deny') {
    phoneVisible.value = false
    uni.showToast({
      title: '您拒绝了授权',
      duration: 2000,
      icon: 'none'
    })
  }
}

const handleConfirm = () => {
  agree.value = true
  visible.value = false
  if (loginStyle.value === 'password') {
    login()
  } else {
    handleOneKeyLogin()
  }
}

onShareAppMessage(() => {
  return {
    title: '集鲜直采',
    imageUrl: '/static/images/share.jpg',
    path: '/pages/login/index'
  }
})

onShareTimeline(() => {
  return {
    title: '集鲜直采',
    imageUrl: '/static/images/share.jpg'
  }
})
</script>

<style scoped lang="scss">
:deep(input) {
  font-weight: bold !important;
}

.login {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: url('https://saas-gateway.jixiansc.com/admin/sys-file/prod-dc-freshx/fcff740993bf4e73b4b85a70767e6adb.png')
    no-repeat;
  background-size: 100% 560rpx;

  :deep(.u-checkbox__label) {
    color: #8a8a8a !important;
  }

  .agreement {
    display: flex;
    justify-content: space-between;
    margin-top: 64rpx;

    .prot {
      color: #04b27c;
      font-size: 24rpx;
    }
  }

  .one-key-login {
    color: #04b27c;
    text-align: center;
    padding-top: 8rpx;
    font-size: 32rpx;

    .one-key-btn {
      :deep(.u-btn) {
        color: #04b27c;
      }
    }
  }

  .phone-button {
    color: #ffffff;
    background: #04b27c;
    font-weight: bold;
    margin-left: 24rpx;
    flex: 1;
    text-decoration: none;
    position: relative;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid rgba(4, 178, 124, 0.6);
    padding: 16rpx 0;
    border-radius: 16rpx;
    box-sizing: border-box;
    height: 84rpx;

    &::after {
      border: none;
    }
  }

  .head {
    display: flex;
    flex-direction: column;
    font-size: 48rpx;
    line-height: 68rpx;
    font-weight: bold;
    height: 200 * 2rpx;
    width: 100%;
    background-size: cover;
    padding: 192rpx 48rpx 0;
    position: relative;

    u-image {
      width: 100%;
      position: absolute;
      height: 100%;
      left: 0;
      top: 0;
      z-index: 0;
    }

    image {
      width: 64rpx;
      height: 64rpx;
      margin-bottom: 32rpx;
    }

    text {
      color: #262626;

      .green {
        color: #039769;
      }
    }
  }

  .shadow {
    width: 100%;
    background: #ffffff;
    box-shadow: 0px -2px 40rpx 0px rgba(6, 184, 128, 0.12);
    border-radius: 32rpx 32rpx 0px 0px;
    position: relative;
    z-index: 2;
  }

  .form {
    flex: 1;
    background-color: #ffffff;
    padding: 0 48rpx;
    position: relative;
    z-index: 2;
    :deep(.u-size-default) {
      height: 96rpx;
      border-radius: 16rpx;
      font-size: 32rpx;
      margin-top: 32rpx;
    }
    :deep(input) {
      font-size: 32rpx !important;
    }
  }
}

.identity-tab {
  display: flex;
  align-items: center;
  justify-content: space-evenly;
  height: 110rpx;
  font-size: 36rpx;
  border-bottom: 1px solid #eee;

  .tab {
    display: flex;
    align-items: center;
    height: 100%;
    padding: 0 20rpx;
  }
}

.tab-active {
  color: #19be6b;
  position: relative;

  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 50%;
    width: 90%;
    transform: translateX(-50%);
    height: 3px;
    background-color: #19be6b;
  }
}
.form :deep(.u-form-item--right__content__slot) {
  position: relative;
}
.hidden_input {
  opacity: 0;
  color: #fff;
  position: absolute;
  left: -9999px;
  top: 0;
  width: 100%;
  height: 1.4rem;
  min-height: 29px;
  font-weight: 400;
}
</style>
<style lang="scss">
@keyframes flashing1 {
  0%,
  24% {
    background-color: unset;
  }
  26%,
  74% {
    background-color: #000;
  }
  76%,
  100% {
    background-color: unset;
  }
}
.show_input {
  position: relative;
  width: 100%;
  height: 1.4rem;
  min-height: 29px;
  font-weight: bold;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding-right: 24px;
  font-size: 32rpx;
  .custom-ph {
    color: #808080;
    font-weight: 400;
  }
  .custom_pw {
    height: 100%;
    color: rgb(38, 38, 38);
  }
  .cursor {
    width: 1px;
    height: 60%;
    animation: flashing1 1s linear infinite;
  }
  .icon {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
  }
}
.divider {
  position: relative;
  height: 40rpx;
  line-height: 40rpx;
  font-size: 24rpx;
  color: #808792;
  text-align: center;
  overflow: hidden;
  margin-top: 40rpx;
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    right: 50%;
    margin-right: 96rpx;
    width: 50%;
    height: 1rpx;
    background-color: #ebecee;
  }
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: 96rpx;
    width: 50%;
    height: 1rpx;
    background-color: #ebecee;
  }
}
.list {
  margin-top: 20rpx;
  display: flex;
  justify-content: space-around;
  .item {
    margin-top: 8rpx;
    font-size: 24rpx;
    line-height: 44rpx;
    color: #808792;
    text-align: center;
    cursor: pointer;
    line-height: 44rpx;
    .icon {
      margin: auto;
      margin-bottom: 8rpx;
      width: 50rpx;
      height: 50rpx;
      border-radius: 100%;
      border-radius: 100%;
      background-color: #fff;
      image {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
    &:hover {
      .icon {
        transform: translateY(-6rpx);
      }
    }
  }
}
</style>
